import React from "react";
import { deepFullCopy, messages, queryCurrencyPrecision } from "share/common";
import { Alert, Button, Popover } from "antd";
import "styles/expense-report/components/expense-detail-alert.scss";
import ListSelector from "components/list-selector";
import chooserData from "share/chooserData";
import SVGIcon from "components/SVGIcon";
import "styles/expense-report/components/expense-associate-application.scss";
import shallowEqual from "containers/expense/component/shallowEqual";
import Condition from "components/condition";
import ResizeTable from "components/resize-table/resize-table";

const { If } = Condition;

class ExpenseAssociateApplication extends React.Component {
  state = {
    value: [],
    visible: false,
    budgetVisible: false,
  };

  budgetColumns = [
    {
      title: messages("common.expense.type") /*费用类型*/,
      dataIndex: "expenseTypeName",
      render: (value) => (value ? <Popover content={value}>{value}</Popover> : "-"),
    },
    {
      title: messages("expense-1.key836") /*行程*/,
      dataIndex: "itinerarySummary",
      width: "50%",
      render: (value) => (value ? <Popover content={value}>{value}</Popover> : "-"),
    },
    {
      title: messages("common.amount") /*金额*/,
      dataIndex: "amount",
      render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode)),
    },
  ];

  budgetSelectTip = (
    <Alert
      showIcon
      type="info"
      style={{ margin: "8px 0" }}
      message={messages("expense-1.key837") /*仅支持选择所选申请单下相同费用类型或父费用类型的预算行*/}
    />
  );

  componentDidMount() {
    if (this.props.value) {
      this.setState({ value: this.props.value });
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.value && !shallowEqual(nextProps.value, this.state.value)) {
      this.setState({ value: nextProps.value });
    }
    // 切换 币种 或 费用类型 时清空预算行
    if (nextProps.currencyCode !== this.props.currencyCode || nextProps.expenseType.id !== this.props.expenseType.id) {
      this.clearBudgetRows();
    }
  }

  // 清空预算行
  clearBudgetRows = () => {
    const { onChange } = this.props;
    const { value } = this.state;
    value[0] && (value[0].budgetDetails = undefined);
    this.setState({ value }, () => onChange && onChange(value));
  };

  onChange = (params) => {
    const { getRequestParticipants, onChange } = this.props;
    let applicationParticipants = [];
    if (params.result && params.result[0]) {
      params.result.map((i) => (applicationParticipants = applicationParticipants.concat(i.applicationParticipants)));
      getRequestParticipants && getRequestParticipants(applicationParticipants);
    }
    this.setState(
      {
        visible: false,
        value: params.result.map((i) => ({ applicationNumber: i.businessCode })) || [],
      },
      () => onChange && onChange(this.state.value)
    );
  };

  handleSelectBudget = (params) => {
    const { onChange } = this.props;
    const { value } = this.state;
    value[0] && (value[0].budgetDetails = params.result);
    this.setState(
      {
        value,
        budgetVisible: false,
      },
      () => onChange && onChange(this.state.value)
    );
  };

  render() {
    const {
      disabled,
      ownerOID,
      expenseType,
      field,
      skipApplication,
      isFromExpenseReport,
      currencyCode,
      businessCode,
    } = this.props;
    const { value, visible, budgetVisible } = this.state;
    const { multiApplicationEnabled, showBudgetDetail } = field.config || {};
    const budgetDetails = (value[0] && value[0].budgetDetails) || [];
    let selectorItem = deepFullCopy(chooserData["my_request"]);
    selectorItem.url = `/api/applications/invoice/refer?expenseTypeId=${expenseType.id}`;
    return (
      <div className="expense-associate-application">
        {!disabled ? (
          <Button type="link" icon="plus" onClick={() => this.setState({ visible: true })}>
            <span>
              {
                value && value.length
                  ? messages("expense-1.key793") /*更改申请单*/
                  : messages("expense-1.key794") /*添加申请单*/
              }
            </span>
          </Button>
        ) : (
          ""
        )}
        <div>
          {value && value.length
            ? value.map((i) => (
                <a
                  onClick={() => skipApplication(typeof i === "string" ? i : i.applicationNumber)}
                  className="expense-associate-application-link"
                >
                  <SVGIcon type="application" />
                  &nbsp;{typeof i === "string" ? i : i.applicationNumber}
                </a>
              ))
            : disabled
            ? "-"
            : ""}
        </div>
        <If value={!disabled && isFromExpenseReport && showBudgetDetail === 1 && value && value.length}>
          <Button type="link" icon="plus" onClick={() => this.setState({ budgetVisible: true })}>
            <span>
              {
                budgetDetails.length
                  ? messages("expense-1.key838") /*更改明细行*/
                  : messages("expense-1.key839") /*添加明细行*/
              }
            </span>
          </Button>
        </If>
        <If value={budgetDetails.length}>
          <ResizeTable
            rowKey="budgetOID"
            columns={this.budgetColumns}
            dataSource={budgetDetails}
            pagination={false}
            size="middle"
            bordered
          />
        </If>
        {!disabled && (
          <ListSelector
            visible={visible}
            selectorItem={selectorItem}
            disabled={field.applicationSource === 0 || !field.editable}
            extraParams={{ applicantOID: ownerOID }}
            labelKey="businessCode"
            valueKey="businessCode"
            selectedData={(value || []).map((item) => ({ businessCode: item && item.applicationNumber }))}
            single={!multiApplicationEnabled}
            maxNum={10}
            placeholder={field.placeholder || messages("common.select") /*请选择*/}
            onOk={this.onChange}
            onCancel={() => this.setState({ visible: false })}
          />
        )}
        <ListSelector
          visible={budgetVisible}
          type="application_budget_list"
          disabled={field.applicationSource === 0 || !field.editable}
          extraParams={{
            applicationNumber: value[0] && value[0].applicationNumber,
            expenseTypeId: expenseType.id,
            currencyCode,
            businessCode,
          }}
          selectedData={budgetDetails.map((item) => ({ budgetOID: item.budgetOID }))}
          valueKey="budgetOID"
          single
          beforeTable={this.budgetSelectTip}
          onOk={this.handleSelectBudget}
          onCancel={() => this.setState({ budgetVisible: false })}
        />
      </div>
    );
  }
}

ExpenseAssociateApplication.propsType = {
  disabled: React.PropTypes.bool, //是否只读
  expenseType: React.PropTypes.object, //费用类型对象
  isFromExpenseReport: React.PropTypes.bool, //是否从报销单中查看的费用详情
  currencyCode: React.PropTypes.string, // 费用当前币种
  businessCode: React.PropTypes.string, // 报销单号
};

ExpenseAssociateApplication.defaultProps = {
  expenseType: {},
  isFromExpenseReport: true,
};

export default ExpenseAssociateApplication;
